package com.haredot.handler;

import com.haredot.result.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class SpfExceptionHandler {

    @ExceptionHandler({BindException.class})
    public R<?> exceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldErrors().get(0);
        Map<String, String> error = new HashMap<>();
        error.put("invalid", fieldError.getDefaultMessage());
        return R.fail(R.StatusCode.BAD).data(error);
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus
    public R<?> exceptionHandler(Exception e){
        return R.fail(R.StatusCode.ERROR).build();
    }
}
